﻿using AutojsController.Config;
using AutojsController.Helpers;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using System.Linq;
using ReactiveUI;

namespace AutojsController.Services
{
    public class ScriptsService: IDBService
    {
        public ScriptsService(IDbContextFactory<DBContext> dbContextFactory) :base(dbContextFactory) { }

        public async Task<List<Script>> GetAllScriptAsync()
        {
            using var db = await dbFactory.CreateDbContextAsync();
            return await db.scripts.ToListAsync();
        }

        public async Task AssignScriptToGroupAsync(int srpId, int grpId)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            var grp = await db.groups.FindAsync(grpId);
            if (grp != null)
            {
                grp.ScriptID = srpId;
                await db.SaveChangesAsync();
            }
        }

        public async Task CreateScriptAsync(string path, string name, ScriptType type)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            if (await db.scripts.AnyAsync(s => s.Name == name))
            {
                throw new DuplicateScriptException(name);
            }
            Script script = new Script()
            {
                Path = path,
                Name = name,
                Type = type
            };
            await db.scripts.AddAsync(script);
            await db.SaveChangesAsync();
        }

        public async Task<bool> IsExistScriptNameAsync(string name)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            return await db.scripts.AnyAsync(s => s.Name == name);
        }

        public async Task<Script?> SetScriptValidationAsync(int srpId, bool validated = true)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            //await db.scripts.Where(s => s.Id == srpId).ExecuteUpdateAsync(setters => 
            //        setters.SetProperty(s => s.Validated, isValidate));
            var script = await db.scripts.FindAsync(srpId);
            if (script != null)
            {
                script.Validated = validated;
                await db.SaveChangesAsync();
                return script;
            }
            return null;
        }

        public async Task DeleteScriptAsync(int srpId)
        {
            using var db = await dbFactory.CreateDbContextAsync();
            await db.scripts.Where(s => s.Id == srpId).ExecuteDeleteAsync();
        }
    }
}
